<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas{
      border:1px solid;
      width:500px;
      height:250px;
      background-color: #fff;
    }
  </style>
</head>
<body>
  <canvas id="canvas" width='1000' height='500' ></canvas>
  <div>
    <button id='save'>保存</button>
    <Button id='clear'>清空</Button>
  </div>
</body>
</html>
<script>
  let canvas = document.getElementsByTagName('canvas')[0];
  let ctx = canvas.getContext('2d');
  let x = 0,y= 0;// 记录鼠标位置的；
  let isDown = false;// 记录鼠标是否按下的
  ctx.fillStyle='#fff';
  ctx.fillRect(0,0,canvas.width,canvas.height)
  canvas.onmousedown = function(e){
    isDown = true;
    x = e.offsetX*2;
    y = e.offsetY*2;
    
    // ctx.beginPath();
    // ctx.moveTo(x,y);
  }
  canvas.onmouseup = function(e){
    isDown = false
  }
  canvas.onmousemove = function(e){
    if(!isDown) return;
    ctx.lineWidth = 5
    ctx.beginPath();
    ctx.moveTo(x,y);
    ctx.lineTo(e.offsetX*2,e.offsetY*2);
    ctx.stroke();
    x = e.offsetX*2;
    y = e.offsetY*2
  }
  canvas.onmouseleave = function(){
    isDown = false
  }
  save.onclick = function(){
    let url = canvas.toDataURL('image/jpeg')// 把canvas转成对应的 png的 base64编码
    console.log(url)
    // 下载需要借助 A标签
    let a = document.createElement('a');
    a.href = url;// 把A标签的href设置成资源
    a.download = '签名' // 对应的是下载的文件的名字
    document.body.appendChild(a);
    a.click()// 主动触发a标签的点击
    a.remove()
  }
  clear.onclick = function(){
    ctx.clearRect(0,0,canvas.width,canvas.height)
  }
</script>